Traversing the Project Tree
This example shows how to traverse the Project Tree for a specific item. This example uses the IProjectTree80 (FindItem, GetItemName, HiddenGroupName) property and methods.
private void ScanTree()
{
try
{
var SGWorld = new SGWorld80();
MessageBox.Show("Click ok to find Vermont item by its path in the tree");
var id = SGWorld.ProjectTree.FindItem("New England\\States\\Vermont");
if (string.IsNullOrEmpty(id))
MessageBox.Show("New England\\States\\Vermont does not exist in tree");
else
MessageBox.Show("Found Vermont with id=" + id);
// root is the first visible item in tree.
var root = SGWorld.ProjectTree.GetNextItem(string.Empty, ItemCode.ROOT);
// if the tree has hidden group, skip it.
// find hidden group by its name. We could also check by HiddenGroupID, which is actually its parent id.
if (SGWorld.ProjectTree.GetItemName(root) == SGWorld.ProjectTree.HiddenGroupName)
root = SGWorld.ProjectTree.GetNextItem(root, ItemCode.NEXT);
var tree = BuildTreeRecursive(root, 1);
MessageBox.Show(tree);
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error: " + ex.Message);
}
}
private string BuildTreeRecursive(string current, int indent)
{
var SGWorld = new SGWorld80();
// build padding
var padding = new string('-', indent * 3);
var result = string.Empty;
// iterate over all siblings of current node
while (string.IsNullOrEmpty(current) == false)
{
// append node name to the tree string
var currentName = SGWorld.ProjectTree.GetItemName(current);
result += padding + currentName + Environment.NewLine;
// if current node is group, recursively build tree from its first child;
if (SGWorld.ProjectTree.IsGroup(current))
{
var child = SGWorld.ProjectTree.GetNextItem(current, ItemCode.CHILD);
result += BuildTreeRecursive(child, indent + 1);
}
// move to next sibling
current = SGWorld.ProjectTree.GetNextItem(current, ItemCode.NEXT);
}
return result;
}